// police_geo表数据
const policeGeoData = require('./updateData/policeGeoData')
const situationData = require('./updateData/situationData')
const policeCarGeoData = require('./updateData/policeCarGeoData')
const actualCompanyGeoData = require('./updateData/actualCompanyGeo')
const actualBuildingGeoData = require('./updateData/actualBuildingGeoData')
const majorMemberGeoData = require('./updateData/majorMemberGeoData')
let dataList = actualCompanyGeoData;
const gps2Ue4 = require('./function/GPSToUe4')
const geohash = require('ngeohash');
const superagent = require('superagent');
const {getDetailAddress, getJurisdiction} = require('./function/common')

//gps
let geojsonData = [];
//ue4
let Ue4Data = [];
//hash
let hashData = [];
//center
let centerData = [];
//ue4center
let ue4centerData = [];

for(let i = 0; i < dataList.position.length; i++) {
    let x = dataList.position[i].split(',')[0]
    let y = dataList.position[i].split(',')[1]
    geojsonData.push([x, y])
    Ue4Data.push(gps2Ue4([x, y]))
    //hash值
    let hash = geohash.encode(y, x, 7);
    hashData.push(hash);
    //反解hash值
    let decodeHash = geohash.decode_bbox(hash);
    //计算hash边界值
    let [minlat, minlon, maxlat, maxlon] = decodeHash;

    //中心点坐标
    let centerGpsX = (maxlon + minlon) / 2;
    let centerGpsY = (maxlat + minlat)/2;
    centerData.push([centerGpsX,centerGpsY]);
    //ue4中心点坐标
    ue4centerData.push(gps2Ue4([centerGpsX,centerGpsY]));
}

let formatGaodeParam = formatGaodeParamFunc(geojsonData);

//格式化数据
let formatResult = addCenterCoordinate(geojsonData);

//添加中心点坐标
function addCenterCoordinate(data){
    //生成对应hash值
    let hashMapList = data.map((item,index) => {
        let [x,y] = item;
        return {
            'index': index,
            'x': x,
            'y': y,
            'hash': geohash.encode(y, x, 7)
        }
    })
    //根据hash分组
    let map = {};
    for(let i = 0;i < hashMapList.length;i++) {
        let hashKey = hashMapList[i].hash;
        if (!map[hashKey]) {
            map[hashKey] = [];
        } else {
            // console.log('cunzai')
        }
        map[hashKey].push(hashMapList[i]);
    }
    //根据同一组计算
    let result = [];
    for (const key in map) {
        // console.log(key, 'key----')
        let valueList = map[key];
        // [
        //     // {x: '',y: '', hash: '', index: ''}
        // ]
        let xList = valueList.map(item => item.x);
        let yList = valueList.map(item => item.y);
        // console.log(xList, '------xList')
        // console.log(yList, '------yList')
        let maxlon = Math.max(...xList);
        let minlon = Math.min(...xList);
        let maxlat = Math.max(...yList);
        let minlat = Math.min(...yList);

        //中心点坐标
        let centerGpsX = (maxlon + minlon) / 2;
        let centerGpsY = (maxlat + minlat) / 2;
        //转化UE4坐标
        // let ue4center = gps2Ue4([centerGpsX,centerGpsY]);

        // console.log([centerGpsX, centerGpsY]);
        // console.log(ue4center)
      
        result = result.concat(valueList.map(item => {
            return {
                'index': item.index,
                'x': item.x,
                'y': item.y,
                'hash': item.hash,
                'center': [centerGpsX, centerGpsY],
                'ue4Center':  gps2Ue4([centerGpsX,centerGpsY])
            }
        }));

    }
    // console.log(result, 'xxxx')
    // 按索引排序
    return result.sort((a, b) => a.index - b.index);
}

start();
async function start(){
    console.log('开始运行...');
    let superagentResult = [];
    console.log('正在请求数据中...');
    for(let i=0;i<formatGaodeParam.length;i++) {
        console.log(`正在进行第${i+1}次请求...`);
        let result = await superagent.get(`https://restapi.amap.com/v3/geocode/regeo?output=json&location=${formatGaodeParam[i]}&key=c00642a14b5ae7c530ccfa8f2f51ef9a&radius=1000&extensions=all&batch=true`).catch((e) => { console.log('获取信息', e); });
        if (!result || !result.text) console.log(`第${i}条高德res为空`);
        let {info, regeocodes:data} = JSON.parse(result.text);
        if (info !== 'OK') {
            console.log('请求数据失败...');
            return;
        }
        superagentResult = superagentResult.concat(data);
    }
    console.log(`请求完成，开始拼装数据...`);
    // console.log(superagentResult, 'superagentResult---')
    let sqlObj = superagentResult.map((item, index) => {
        return {
            // 'INDEX_id': index + START_INDEX, //索引开始
            'adcode': item.addressComponent.adcode,
            'province': item.addressComponent.province,
            'city': item.addressComponent.city,
            'district': item.addressComponent.district,
            'town_ship': item.addressComponent.township,
            'jurisdiction': getJurisdiction(item.addressComponent.township),
            'detail_address': getDetailAddress(item.formatted_address, item.addressComponent.province, item.addressComponent.city, item.addressComponent.district, item.addressComponent.township),
            // 'lng_x': geojsonData[index][0],
            // 'lat_y': geojsonData[index][1],
            // 'geo_hash': hashData[index],
            'lng_x': formatResult[index]['x'],
            'lat_y': formatResult[index]['y'],
            'geo_hash': formatResult[index]['hash'],
            'internal_coordinate_x': Ue4Data[index][0],
            'internal_coordinate_y': Ue4Data[index][1],
            // 'center_x': centerData[index][0],
            // 'center_y': centerData[index][1],
            // 'internal_coordinate_center_x': ue4centerData[index][0],
            // 'internal_coordinate_center_y': ue4centerData[index][1],
            'center_x': formatResult[index]['center'][0],
            'center_y': formatResult[index]['center'][1],
            'internal_coordinate_center_x': formatResult[index]['ue4Center'][0],
            'internal_coordinate_center_y': formatResult[index]['ue4Center'][1],
            'format_address': item.formatted_address
        }
    })

    let sqlObjChange = sqlObj.map((ele,index) => {
        let tmp = JSON.parse(JSON.stringify(ele))
        let idArr = dataList.id.slice(0, dataList.position.length)
        idArr.forEach((item, i) => {
            if (index === i) {
                tmp.id = item
                // tmp.jurisdiction = 'MA_JIA_WAN'
                tmp.jurisdiction = 'ZHANG_BU'
            }
        })
        return tmp;
    })
    console.log(`拼装数据完成，准备连接数据库写入数据...`);

    console.log(sqlObjChange, 'sqlObj-------')

    //数据库配置
    let pg = require('pg');
    
    let client = new pg.Client('postgres://postgres:herin123@localhost:5432/police');
    client.connect(async function(err, client, done){
        if (err) {
            console.log('连接postgresql出错');
        } else {
            console.log('连接postgresql成功');
        
            for(let i=0;i<sqlObjChange.length;i++) {
                let {
                    id, 
                    adcode, 
                    province, 
                    city, 
                    district, 
                    town_ship, 
                    jurisdiction, 
                    detail_address, 
                    lng_x,
                    lat_y,
                    geo_hash,
                    center_x,
                    center_y,
                    internal_coordinate_x,
                    internal_coordinate_y,
                    internal_coordinate_center_x,
                    internal_coordinate_center_y,
                    format_address
                } = sqlObjChange[i];

                // police_geo
                // await client.query(`UPDATE police_geo SET adcode=$2,province=$3,city=$4,district=$5,town_ship=$6,jurisdiction=$7,detail_address=$8,lng_x=$9,lat_y=$10,internal_coordinate_x=$11,internal_coordinate_y=$12,format_address=$13 WHERE id=$1`, [ 
                //         id, //1
                //         adcode,//2 
                //         province, //3
                //         city, //4
                //         district,//5 
                //         town_ship, //6
                //         jurisdiction, //7
                //         detail_address, //8
                //         lng_x,//9
                //         lat_y,//10
                //         internal_coordinate_x,//14
                //         internal_coordinate_y,//15
                //         format_address]//18
                // );

                //situation_geo
                // await client.query(`UPDATE situation_geo SET adcode=$2,province=$3,city=$4,district=$5,town_ship=$6,jurisdiction=$7,detail_address=$8,lng_x=$9,lat_y=$10,geo_hash=$11,center_x=$12,center_y=$13,internal_coordinate_x=$14,internal_coordinate_y=$15,internal_coordinate_center_x=$16,internal_coordinate_center_y=$17,format_address=$18 WHERE id=$1`, [ 
                //     id, //1
                //     adcode,//2 
                //     province, //3
                //     city, //4
                //     district,//5 
                //     town_ship, //6
                //     jurisdiction, //7
                //     detail_address, //8
                //     lng_x,//9
                //     lat_y,//10
                //     geo_hash, //11
                //     center_x,//12
                //     center_y,//13
                //     internal_coordinate_x,//14
                //     internal_coordinate_y,//15
                //     internal_coordinate_center_x,//16
                //     internal_coordinate_center_y,//17
                //     format_address]//18
                // );

                //police_car_geo
                // await client.query(`UPDATE police_car_geo SET adcode=$2,province=$3,city=$4,district=$5,town_ship=$6,jurisdiction=$7,detail_address=$8,lng_x=$9,lat_y=$10,internal_coordinate_x=$11,internal_coordinate_y=$12,format_address=$13 WHERE id=$1`, [ 
                //         id, //1
                //         adcode,//2 
                //         province, //3
                //         city, //4
                //         district,//5 
                //         town_ship, //6
                //         jurisdiction, //7
                //         detail_address, //8
                //         lng_x,//9
                //         lat_y,//10
                //         internal_coordinate_x,//14
                //         internal_coordinate_y,//15
                //         format_address]//18
                // );

                //actual_company_geo
                await client.query(`UPDATE actual_company_geo SET adcode=$2,province=$3,city=$4,district=$5,town_ship=$6,jurisdiction=$7,detail_address=$8,lng_x=$9,lat_y=$10,geo_hash=$11,center_x=$12,center_y=$13,internal_coordinate_x=$14,internal_coordinate_y=$15,internal_coordinate_center_x=$16,internal_coordinate_center_y=$17,format_address=$18 WHERE id=$1`, [ 
                    id, //1
                    adcode,//2 
                    province, //3
                    city, //4
                    district,//5 
                    town_ship, //6
                    jurisdiction, //7
                    detail_address, //8
                    lng_x,//9
                    lat_y,//10
                    geo_hash, //11
                    center_x,//12
                    center_y,//13
                    internal_coordinate_x,//14
                    internal_coordinate_y,//15
                    internal_coordinate_center_x,//16
                    internal_coordinate_center_y,//17
                    format_address]//18
                );

                //actual_building_geo
                // await client.query(`UPDATE actual_building_geo SET adcode=$2,province=$3,city=$4,district=$5,town_ship=$6,jurisdiction=$7,detail_address=$8,lng_x=$9,lat_y=$10,geo_hash=$11,center_x=$12,center_y=$13,internal_coordinate_x=$14,internal_coordinate_y=$15,internal_coordinate_center_x=$16,internal_coordinate_center_y=$17,format_address=$18 WHERE id=$1`, [ 
                //     id, //1
                //     adcode,//2 
                //     province, //3
                //     city, //4
                //     district,//5 
                //     town_ship, //6
                //     jurisdiction, //7
                //     detail_address, //8
                //     lng_x,//9
                //     lat_y,//10
                //     geo_hash, //11
                //     center_x,//12
                //     center_y,//13
                //     internal_coordinate_x,//14
                //     internal_coordinate_y,//15
                //     internal_coordinate_center_x,//16
                //     internal_coordinate_center_y,//17
                //     format_address]//18
                // );

                //major_member_geo
                // await client.query(`UPDATE major_member_geo SET adcode=$2,province=$3,city=$4,district=$5,town_ship=$6,jurisdiction=$7,detail_address=$8,lng_x=$9,lat_y=$10,geo_hash=$11,center_x=$12,center_y=$13,internal_coordinate_x=$14,internal_coordinate_y=$15,internal_coordinate_center_x=$16,internal_coordinate_center_y=$17,format_address=$18 WHERE id=$1`, [ 
                //     id, //1
                //     adcode,//2 
                //     province, //3
                //     city, //4
                //     district,//5 
                //     town_ship, //6
                //     jurisdiction, //7
                //     detail_address, //8
                //     lng_x,//9
                //     lat_y,//10
                //     geo_hash, //11
                //     center_x,//12
                //     center_y,//13
                //     internal_coordinate_x,//14
                //     internal_coordinate_y,//15
                //     internal_coordinate_center_x,//16
                //     internal_coordinate_center_y,//17
                //     format_address]//18
                // );

                console.log(`更新第${i+1}条数据成功！`)
            }

        }

        console.log('完成！')
    });
}



/**
 * 格式化高德请求参数
 * @param {Array} geojsonDataInput 
 */
 function formatGaodeParamFunc(geojsonDataInput){
    let gpsStringList = geojsonDataInput.map(([x,y]) => {
        return x+','+y;
    });
    
    let paramList = []; //请求参数

    let item = '';
    let paramListIndex = 0;
    const SLICE_LENGTH = 20; //最大请求的坐标点个数
    for(let i=0;i<gpsStringList.length;i++) {
        if ( i < SLICE_LENGTH*(paramListIndex+1)) {
            item += i === SLICE_LENGTH*paramListIndex ? gpsStringList[i] : '|' + gpsStringList[i];
            if (i === gpsStringList.length - 1) {
                paramList.push(item);
            }
        } else {
            paramList.push(item);
            paramListIndex++;
            item = gpsStringList[i];
        }
    }
    console.log('格式化高德数据：',paramList)
    return paramList;
}